﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Dependency;
using Xugege.AbpExtension.Application.Extension.DataDictionary.Dto;
using Xugege.AbpExtension.Core.Extension.DataManager;

namespace Xugege.AbpExtension.Application.Extension.DataDictionary
{


    public class DictionaryHelper : ITransientDependency
    {
        private readonly DataDictionarySetting _dictionarySetting;

        public DictionaryHelper(DataDictionarySetting dictionarySetting)
        {
            _dictionarySetting = dictionarySetting;
        }
        /// <summary>
        /// 根据代码规则生成树结构列表
        /// </summary>
        /// <param name="list"></param>
        /// <param name="rule"></param>
        /// <returns></returns>
        public IList<DictionaryOutputDto> CreateDictionaryTreeList(
            IList<DictionaryOutputDto> list, string rule)
        {                        
            IList<string> ruleSplits = rule.Split(_dictionarySetting.LevelRuleSplit).ToList();
            if (ruleSplits.Any(m => !IsNumber(m)))
            {
                throw new Exception("代码规则设置不正确");
            }
            IList<int> ruleSplitsInt = ruleSplits.Select(int.Parse).ToList();
            IList<int> levelLengths = new List<int>();
            for (int i = 0; i < ruleSplitsInt.Count; i++)
            {
                var level = ruleSplitsInt[i];
                for (int j = 0; j < i; j++)
                {
                    var oldLevel = ruleSplitsInt[j];
                    level += oldLevel;
                }
                levelLengths.Add(level);
            }

            foreach (var dto in list)
            {

                int levelOrder = levelLengths.IndexOf(dto.Code.Length);
                if (levelOrder == 0)
                {
                    dto.ParentCode = null;
                }
                else
                {
                    var parentLevelLength = dto.Code.Length - ruleSplitsInt[levelOrder];
                    dto.ParentCode = dto.Code.Substring(0, parentLevelLength);
                    var parent = list.FirstOrDefault(m => m.Code.Length == parentLevelLength && m.Code == dto.ParentCode);
                    if (parent == null)
                    {
                        //如果没有找到对应的父节点 自身作为父节点
                        dto.ParentCode = null;
                    }
                    else
                    {
                        var brothers = parent.Children ?? new List<DictionaryOutputDto>();
                        brothers.Add(dto);
                    }
                }
            }
            
            return list;

        }

        public bool IsNumber(string source)
        {
            int target = 0;
            return int.TryParse(source, out target);
        }
    }
}
